﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Blabber.Data;
using System.IO;
using System.Data;
using System.Runtime.InteropServices;

namespace Blabber.Client
{
    /// <summary>
    /// Interaction logic for WindowChat.xaml
    /// </summary>
    public partial class WindowChat : Window
    {
        agsXMPP.Jid _jid;
        CommunicationData _communicator;
        DataSetMessage _messages;

        Blabber.Data.DataSetBlabber.RosterItemRow _rosterRow;

        public event EventHandler MessageItemDoubleClick;

        public WindowChat()
        {
            InitializeComponent();

            _messages = new DataSetMessage();

            listBoxMessages.DataContext = _messages.Message;

            this.Closed += new EventHandler(WindowChat_Closed);
        }

        void WindowChat_Closed(object sender, EventArgs e)
        {
            if (null != _jid)
            {
                Blabber.Client.Properties.Settings.Default.ChatWindowLocation = new System.Drawing.Point((int)this.Left, (int)this.Top);
                Blabber.Client.Properties.Settings.Default.ChatWindowSize = new System.Drawing.Size((int)this.Width, (int)this.Height);
            }
            else
            {
                Blabber.Client.Properties.Settings.Default.CommunityWindowLocation = new System.Drawing.Point((int)this.Left, (int)this.Top);
                Blabber.Client.Properties.Settings.Default.CommunityWindowSize = new System.Drawing.Size((int)this.Width, (int)this.Height);
            }

            if (!Directory.Exists("chats"))
                Directory.CreateDirectory("chats");

            if (null != _jid)
                _messages.WriteXml(string.Format(".\\chats\\{0}_{1}.xml", _jid.User, DateTime.Now.ToString("dd-MM-yy-hhmmss")));
        }

        public agsXMPP.Jid Jid
        {
            get { return _jid; }
            set 
            { 
                _jid = value;
                if (null != _jid)
                {
                    chatTextGrid.Visibility = Visibility.Visible;
                    Title = _jid.Bare;
                    _rosterRow = _communicator.Data.RosterItem.FindByJID(_jid.Bare);

                    detailExpander.DataContext = _rosterRow;
                }
                else
                {
                    chatTextGrid.Visibility = Visibility.Collapsed;
                    Title = "Community Messages";
                }
            }
        }

        public CommunicationData Communicator
        {
            get { return _communicator; }
            set { _communicator = value; }
        }

        public Blabber.Data.DataSetBlabber.RosterItemRow RosterRow
        {
            get { return _rosterRow; }
        }

        public DataSetMessage Messages
        {
            get { return _messages; }
        }

        [DllImport("user32.dll")] public static extern bool MessageBeep(int beep);  

        public void PostMessage(string body, string from, string to, DateTime messageTime)
        {
            Blabber.Data.DataSetMessage.MessageRow row = _messages.Message.NewMessageRow();
            row.Body = body;
            row.From = from;
            row.To = to;
            row.MessageTime = messageTime;

            Blabber.Data.DataSetBlabber.RosterItemRow rosterRow;
            rosterRow = _communicator.Data.RosterItem.FindByJID(from);

            if (null != rosterRow)
            {
                if (!(rosterRow["Image"] is DBNull))
                {
                    if (null != rosterRow.Image)
                        row.Image = rosterRow.Image;
                }
            }

            _messages.Message.AddMessageRow(row);

            if (listBoxMessages.Items.Count > 0)
                listBoxMessages.ScrollIntoView(listBoxMessages.Items[listBoxMessages.Items.Count - 1]);

            if ((_jid == null) && (this.WindowState == WindowState.Minimized))
                this.WindowState = WindowState.Normal;

            if (!this.IsFocused)
            {
                MessageBeep(-1);
                Show();
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            _communicator.SendMessage(_jid, messageSend.Text);

            Blabber.Data.DataSetMessage.MessageRow row = _messages.Message.NewMessageRow();
            row.Body = messageSend.Text;
            row.To = _jid.Bare;
            row.MessageTime = DateTime.Now;

            Blabber.Data.DataSetBlabber.RosterItemRow rosterRow;
            rosterRow = _communicator.Data.RosterItem.FindByJID(_jid.Bare);
            if (null != rosterRow)
            {
                row.From = rosterRow.FromJID;
                Blabber.Data.DataSetModel.ConnectionRow connectionRow = _communicator.Model.Connection.FindByJID(rosterRow.FromJID);
                if (null != connectionRow)
                {
                    row.Image = connectionRow.Image;
                }
            }

            _messages.Message.AddMessageRow(row);

            messageSend.Text = string.Empty;
            messageSend.Focus();

            if (listBoxMessages.Items.Count > 0)
                listBoxMessages.ScrollIntoView(listBoxMessages.Items[listBoxMessages.Items.Count - 1]); 
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (null != _jid)
            {
                this.Left = Blabber.Client.Properties.Settings.Default.ChatWindowLocation.X;
                this.Top = Blabber.Client.Properties.Settings.Default.ChatWindowLocation.Y;

                this.Height = Blabber.Client.Properties.Settings.Default.ChatWindowSize.Height;
                this.Width = Blabber.Client.Properties.Settings.Default.ChatWindowSize.Width;
            }
            else
            {
                this.Left = Blabber.Client.Properties.Settings.Default.CommunityWindowLocation.X;
                this.Top = Blabber.Client.Properties.Settings.Default.CommunityWindowLocation.Y;

                this.Height = Blabber.Client.Properties.Settings.Default.CommunityWindowSize.Height;
                this.Width = Blabber.Client.Properties.Settings.Default.CommunityWindowSize.Width;
            }

            messageSend.Focus();
        }

        private void messageListBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            ListBox listView = (sender as ListBox);
            if (listView.SelectedItem is DataRowView)
            {
                Blabber.Data.DataSetMessage.MessageRow row = ((listView.SelectedItem as DataRowView).Row as Blabber.Data.DataSetMessage.MessageRow);

                if (null != MessageItemDoubleClick)
                    MessageItemDoubleClick(row, new EventArgs());

            }
        }

    }
}
